package com.moons.settings.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.text.Layout;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import com.moons.settings.R;
import com.moons.settings.config.ARCommon;
import com.moons.settings.config.ARHidTransfer;
import com.moons.settings.config.DemoConfig;
import com.moons.settings.dialog.FileChooseDialog;
//import cn.artosyn.aruvclib.ARCommon;
//import cn.artosyn.aruvclib.ARHidTransfer;

public class CameraConfigActivity extends AppCompatActivity implements ARHidTransfer.StatusCallback,FileChooseDialog.NoticeDialogListener {

    private static final String TAG = CameraConfigActivity.class.getSimpleName();

    ARHidTransfer hidTransfer;

    private EditText mEditTextUcmd;
    private TextView mTextViewLog;
    private ProgressBar progressBar;
    private EditText editText_blurThreshold;
    private EditText editText_frontThreshold;
    private EditText editText_scoreThreshold;
    private EditText editText_heightMaxValue;
    private EditText editText_heightMinValue;
    private EditText editText_widthMaxValue;
    private EditText editText_widthMinValue;
    private EditText editText_pitchMaxValue;
    private EditText editText_pitchMinValue;
    private EditText editText_rollMaxValue;
    private EditText editText_rollMinValue;
    private EditText editText_yawMaxValue;
    private EditText editText_yawMinValue;
    private Switch switch_faceAEEnabled;
    private Switch switch_attributeRecog;
    private Switch switch_attributeTrack;
    private Switch switch_countAlgorithm;
    private EditText editText_scoringInterval;

    int transMode;

    Gson gson = new Gson();

    private int mLastHidConfCmd = -1;
    private boolean bNeedRebootUVC = false;

    public static boolean uvcUpgrade = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_config);

        hidTransfer = ARHidTransfer.instance();
        hidTransfer.init(this);  //ARHid传送实例
        hidTransfer.register();
        hidTransfer.addCallback(statusCallback); //消息回调

        mEditTextUcmd = findViewById(R.id.editText_ucmd);
        mTextViewLog = findViewById(R.id.textView_log);
        mTextViewLog.setMovementMethod(new ScrollingMovementMethod());
        progressBar = findViewById(R.id.progressBar);

        editText_blurThreshold = findViewById(R.id.editText_blurThreshold);
        editText_frontThreshold = findViewById(R.id.editText_frontThreshold);
        editText_scoreThreshold = findViewById(R.id.editText_scoreThreshold);
        editText_heightMaxValue = findViewById(R.id.editText_heightMaxValue);
        editText_heightMinValue = findViewById(R.id.editText_heightMinValue);
        editText_widthMaxValue = findViewById(R.id.editText_widthMaxValue);
        editText_widthMinValue = findViewById(R.id.editText_widthMinValue);
        editText_pitchMaxValue = findViewById(R.id.editText_pitchMaxValue);
        editText_pitchMinValue = findViewById(R.id.editText_pitchMinValue);
        editText_rollMaxValue = findViewById(R.id.editText_rollMaxValue);
        editText_rollMinValue = findViewById(R.id.editText_rollMinValue);
        editText_yawMaxValue = findViewById(R.id.editText_yawMaxValue);
        editText_yawMinValue = findViewById(R.id.editText_yawMinValue);
        switch_faceAEEnabled = findViewById(R.id.switch_faceAEEnabled);
        switch_attributeRecog = findViewById(R.id.switch_attributeRecog);
        switch_attributeTrack = findViewById(R.id.switch_attributeTrack);
        switch_countAlgorithm = findViewById(R.id.switch_countAlgorithm);
        editText_scoringInterval = findViewById(R.id.editText_scoringInterval);

        mEditTextUcmd.setOnEditorActionListener(
                new EditText.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                        if (actionId == EditorInfo.IME_ACTION_SEARCH ||
                                actionId == EditorInfo.IME_ACTION_DONE ||
                                keyEvent != null &&
                                        keyEvent.getAction() == KeyEvent.ACTION_DOWN &&
                                        keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                            if (keyEvent == null || !keyEvent.isShiftPressed()) {
                                // the user is done typing.
                                String scmd = mEditTextUcmd.getText().toString();
                                if(scmd.isEmpty())
                                    return false;
                                if(hidTransfer.SendUCmd(scmd))
                                    mlog("cmd:"+scmd);
                                else{
                                    mlog("cmd failed:"+scmd);
                                }
                                return false; // consume.
                            }
                        }
                        return false; // pass on to other listeners.
                    }
                }
        );

    }

    @Override
    protected void onStart() {
        super.onStart();
        if(hidTransfer.Open()){
            mlog("Hid open success");
        }else{
            mlog("Hid open failed");
        }
    }

    @Override
    protected void onResume() {
        DemoConfig.instance().isCamConfigMode = true;
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hidTransfer.Close();
        hidTransfer.unregister();
        hidTransfer.removeCallback();
        DemoConfig.instance().isCamConfigMode = false;
    }

    ARHidTransfer.StatusCallback statusCallback = new ARHidTransfer.StatusCallback() {
        @Override
        public void onStatusChange(ARCommon.LOG_MSG_TYPE msg_type, String msg, int process) {
            final ARCommon.LOG_MSG_TYPE msg_type1 = msg_type;
            final String msg1 = msg;
            final int process1 = process;
//            Log.d(TAG," =========msgtype===="+msg_type1);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    switch (msg_type1){
                        case HID_TRANS_STATUS:
                            mlog(msg1);
                            break;
                        case HID_TRANS_PROGRESS:
                            progressBar.setProgress(process1);
                            break;
                        case HID_UPGRADE_STATUS:
                            mlog(msg1);
                            if(msg1.contains("complete")){
                                uvcUpgrade = false;
                            }
                            else
                                uvcUpgrade = true;
                            break;
                        case HID_UCMD_RET:
                            mlog(msg1);
                            break;
                        case HID_GIFO_RET:
                            DemoConfig.instance().uvcDeviceInfo = msg1;
                            Log.d(TAG, msg1);
                            break;
                        case HID_CONF_RET:
                            //Log.d(TAG, "msg1: "+msg1);
                            if(msg1.substring(0,6).contains("config")){
                                mlog(msg1);
                                if(mLastHidConfCmd==ARCommon.ARSTACK_CONF_CMD_SET_COMMON_SETTING&&msg1.contains("ok")){
                                    if(bNeedRebootUVC) {
                                        mlog("waiting for reboot...");
                                        final Handler handler = new Handler();
                                        handler.postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (hidTransfer.rebootUVC()) {
                                                    mlog("send reboot uvc command success");
                                                } else {
                                                    mlog("send reboot uvc command failed");
                                                }
                                            }
                                        }, 7000);
                                    }
                                }
                                break;
                            }
                            switch (mLastHidConfCmd) {
                                case ARCommon.ARSTACK_CONF_CMD_GET_FACE_FILTER:{
                                    Common.ARConf_RetData retData = gson.fromJson(msg1, Common.ARConf_RetData.class);
                                    try {
                                        Log.d(TAG, "retData.data: " + retData.data.toString());
                                        JSONObject json = new JSONObject(retData.data.toString());
                                        JSONObject captureFilter = json.getJSONObject("captureFilter");
                                        editText_blurThreshold.setText(String.valueOf(captureFilter.getInt("blurThreshold")));
                                        editText_frontThreshold.setText(String.valueOf(captureFilter.getInt("frontThreshold")));
                                        editText_scoreThreshold.setText(String.valueOf(captureFilter.getInt("scoreThreshold")));
                                        editText_heightMaxValue.setText(String.valueOf(captureFilter.getInt("heightMaxValue")));
                                        editText_heightMinValue.setText(String.valueOf(captureFilter.getInt("heightMinValue")));
                                        editText_widthMaxValue.setText(String.valueOf(captureFilter.getInt("widthMaxValue")));
                                        editText_widthMinValue.setText(String.valueOf(captureFilter.getInt("widthMinValue")));
                                        editText_pitchMaxValue.setText(String.valueOf(captureFilter.getInt("pitchMaxValue")));
                                        editText_pitchMinValue.setText(String.valueOf(captureFilter.getInt("pitchMinValue")));
                                        editText_rollMaxValue.setText(String.valueOf(captureFilter.getInt("rollMaxValue")));
                                        editText_rollMinValue.setText(String.valueOf(captureFilter.getInt("rollMinValue")));
                                        editText_yawMaxValue.setText(String.valueOf(captureFilter.getInt("yawMaxValue")));
                                        editText_yawMinValue.setText(String.valueOf(captureFilter.getInt("yawMinValue")));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                                break;
                                case ARCommon.ARSTACK_CONF_CMD_GET_COMMON_SETTING:{
                                    Common.ARConf_RetData retData = gson.fromJson(msg1, Common.ARConf_RetData.class);
                                    try {
                                        Log.d(TAG, "retData.data: " + retData.data.toString());
                                        JSONObject json = new JSONObject(retData.data.toString());
                                        JSONObject commonSettings = json.getJSONObject("commonSettings");
                                        switch_faceAEEnabled.setChecked(commonSettings.getBoolean("faceAEEnabled"));
                                        switch_attributeRecog.setChecked(commonSettings.getBoolean("attributeRecog"));
                                        switch_attributeTrack.setChecked(commonSettings.getBoolean("attributeTrack"));
                                        switch_countAlgorithm.setChecked(commonSettings.getBoolean("countAlgorithm"));
                                        editText_scoringInterval.setText(String.valueOf(commonSettings.getInt("scoringInterval")));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    break;
                                }
                                default:
                                    break;
                            }
                        default:
                            break;
                    }
                }
            });
        }

    };

    boolean bret;
    public void onClick(View item) {
        switch (item.getId()) {
            case R.id.imageButton_back:
                onBackPressed();
                break;
            case R.id.button_usb:
                if(hidTransfer.Open()){
                   mlog("Hid open success");
                }else{
                    mlog("Hid open failed");
                }
                break;
            case R.id.button_upgrade:
                transMode=0;
                FileChooseDialog fileDialog =new FileChooseDialog();
                fileDialog.show(getSupportFragmentManager(), "fileDialog");
                break;
            case R.id.button_sendfile:
                transMode = 1;
                FileChooseDialog fileDialog1 =new FileChooseDialog();
                fileDialog1.show(getSupportFragmentManager(), "fileDialog");
                break;
            case R.id.button_startHeart:
                boolean bret1 = hidTransfer.startHeart();
                mlog("开启心跳 "+bret1);
                break;
            case R.id.button_stopHeart:
                boolean bret2 = hidTransfer.stopHeart();
                mlog("关闭心跳 "+bret2);
                break;

            case R.id.button_getCaptureFilter:
                bret = hidTransfer.sendArstackConfig(ARCommon.ARSTACK_CONF_CMD_GET_FACE_FILTER,null);
                if(bret) mLastHidConfCmd = ARCommon.ARSTACK_CONF_CMD_GET_FACE_FILTER;
                else mlog("send config failed");
                break;
            case R.id.button_setCaptureFilter: {
                setCaptureFilter();
                break;
            }
            case R.id.button_getCommonSetting:{
                bret = hidTransfer.sendArstackConfig(ARCommon.ARSTACK_CONF_CMD_GET_COMMON_SETTING,null);
                if(bret)
                {
                    mLastHidConfCmd = ARCommon.ARSTACK_CONF_CMD_GET_COMMON_SETTING;
                }
                else mlog("send config failed");
                break;
            }
            case R.id.button_setCommonSetting2:
            case R.id.button_setCommonSetting:{
                if(item.getId()== R.id.button_setCommonSetting2)
                    bNeedRebootUVC = false;
                else
                    bNeedRebootUVC = true;
                JSONObject main = new JSONObject();
                JSONObject commonSettings = new JSONObject();
                try {
                    commonSettings.put("faceAEEnabled", String.valueOf(switch_faceAEEnabled.isChecked()));
                    commonSettings.put("attributeRecog", String.valueOf(switch_attributeRecog.isChecked()));
                    commonSettings.put("attributeTrack", String.valueOf(switch_attributeTrack.isChecked()));
                    commonSettings.put("countAlgorithm", String.valueOf(switch_countAlgorithm.isChecked()));
                    commonSettings.put("scoringInterval", Integer.parseInt(editText_scoringInterval.getText().toString()));
                    main.put("commonSettings", commonSettings);
                    bret = hidTransfer.sendArstackConfig(ARCommon.ARSTACK_CONF_CMD_SET_COMMON_SETTING, main.toString().getBytes());
                    if (bret) {
                        mLastHidConfCmd = ARCommon.ARSTACK_CONF_CMD_SET_COMMON_SETTING;
                        mlog("send common setting config success");
                    }
                    else mlog("send config failed");
                } catch (JSONException e) {
                    e.printStackTrace();
                    mlog("json转换错误");
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    mlog("参数格式错误");
                }
                break;
            }
            case R.id.button_setDefaultCaptureFilter: {
                editText_blurThreshold.setText("70");
                editText_frontThreshold.setText("50");
                editText_scoreThreshold.setText("10");
                editText_heightMaxValue.setText("400");
                editText_heightMinValue.setText("40");
                editText_widthMaxValue.setText("400");
                editText_widthMinValue.setText("40");
                editText_pitchMaxValue.setText("30");
                editText_pitchMinValue.setText("-30");
                editText_rollMaxValue.setText("30");
                editText_rollMinValue.setText("-30");
                editText_yawMaxValue.setText("30");
                editText_yawMinValue.setText("-30");
                setCaptureFilter();
                break;
            }
            case R.id.button_CamSrcMirrorEnable:{
                if(hidTransfer.SendUCmd("test_cam_src --enable_mirror 1"))
                    mlog("send enable mirror command ok");
                else{
                    mlog("send enable mirror command fail");
                }
                break;
            }
            case R.id.button_CamSrcMirrorDisable:{
                if(hidTransfer.SendUCmd("test_cam_src --enable_mirror 0"))
                    mlog("send disable mirror command ok");
                else{
                    mlog("send disable mirror command fail");
                }
                break;
            }
            case R.id.button_CamSrcFlipEnable:{
                if(hidTransfer.SendUCmd("test_cam_src --enable_flip 1"))
                    mlog("send enable flip command ok");
                else{
                    mlog("send enable flip command fail");
                }
                break;
            }
            case R.id.button_CamSrcFlipDisable:{
                if(hidTransfer.SendUCmd("test_cam_src --enable_flip 0"))
                    mlog("send disable flip command ok");
                else{
                    mlog("send disable flip command fail");
                }
                break;
            }
            default:
                break;
        }
    }

    private void setCaptureFilter(){
        JSONObject main = new JSONObject();
        JSONObject captureFilter = new JSONObject();
        try {
            captureFilter.put("blurThreshold", Integer.parseInt(editText_blurThreshold.getText().toString()));
            captureFilter.put("frontThreshold", Integer.parseInt(editText_frontThreshold.getText().toString()));
            captureFilter.put("scoreThreshold", Integer.parseInt(editText_scoreThreshold.getText().toString()));
            captureFilter.put("heightMaxValue", Integer.parseInt(editText_heightMaxValue.getText().toString()));
            captureFilter.put("heightMinValue", Integer.parseInt(editText_heightMinValue.getText().toString()));
            captureFilter.put("widthMaxValue", Integer.parseInt(editText_widthMaxValue.getText().toString()));
            captureFilter.put("widthMinValue", Integer.parseInt(editText_widthMinValue.getText().toString()));
            captureFilter.put("pitchMaxValue", Integer.parseInt(editText_pitchMaxValue.getText().toString()));
            captureFilter.put("pitchMinValue", Integer.parseInt(editText_pitchMinValue.getText().toString()));
            captureFilter.put("rollMaxValue", Integer.parseInt(editText_rollMaxValue.getText().toString()));
            captureFilter.put("rollMinValue", Integer.parseInt(editText_rollMinValue.getText().toString()));
            captureFilter.put("yawMaxValue", Integer.parseInt(editText_yawMaxValue.getText().toString()));
            captureFilter.put("yawMinValue", Integer.parseInt(editText_yawMinValue.getText().toString()));
            main.put("captureFilter", captureFilter);
            bret = hidTransfer.sendArstackConfig(ARCommon.ARSTACK_CONF_CMD_SET_FACE_FILTER, main.toString().getBytes());
            if (bret) mLastHidConfCmd = ARCommon.ARSTACK_CONF_CMD_SET_FACE_FILTER;
            else mlog("send config failed");
        } catch (JSONException e) {
            e.printStackTrace();
            mlog("json转换错误");
        } catch (NumberFormatException e) {
            e.printStackTrace();
            mlog("参数格式错误");
        }
    }

    public void mlog(String msg)
    {
        mTextViewLog.append("-"+msg+"\n");
        Log.d(TAG,"========"+"-"+msg+"\n");
        if(mTextViewLog.getLineCount()>500)
        {
            mTextViewLog.setText("");
        }
        final Layout layout =  mTextViewLog.getLayout();
        if(layout==null){
            return;
        }
        final int scrollAmount = layout.getLineTop(mTextViewLog.getLineCount())
                - mTextViewLog.getHeight();
        if (scrollAmount > 0)
            mTextViewLog.scrollTo(0, scrollAmount);
        else
            mTextViewLog.scrollTo(0, 0);
    }

    @Override
    public void onStatusChange(ARCommon.LOG_MSG_TYPE msg_type, String msg, int process) {
        final ARCommon.LOG_MSG_TYPE msg_type1 = msg_type;
        final String msg1 = msg;
        final int process1 = process;
        Log.d(TAG," =========msgtype===="+msg_type1);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switch (msg_type1){
                    case HID_TRANS_STATUS:
                        mlog(msg1);
                        break;
                    case HID_TRANS_PROGRESS:
                        progressBar.setProgress(process1);
                        break;
                    case HID_UPGRADE_STATUS:
                        mlog(msg1);
                        if(msg1.contains("complete")){
                            uvcUpgrade = false;
                        }
                        else
                            uvcUpgrade = true;
                        break;
                    case HID_UCMD_RET:
                        mlog(msg1);
                        break;
                    case HID_GIFO_RET:
                        DemoConfig.instance().uvcDeviceInfo = msg1;
                        Log.d(TAG, msg1);
                        break;
                    case HID_CONF_RET:
                        //Log.d(TAG, "msg1: "+msg1);
                        if(msg1.substring(0,6).contains("config")){
                            mlog(msg1);
                            if(mLastHidConfCmd==ARCommon.ARSTACK_CONF_CMD_SET_COMMON_SETTING&&msg1.contains("ok")){
                                if(bNeedRebootUVC) {
                                    mlog("waiting for reboot...");
                                    final Handler handler = new Handler();
                                    handler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (hidTransfer.rebootUVC()) {
                                                mlog("send reboot uvc command success");
                                            } else {
                                                mlog("send reboot uvc command failed");
                                            }
                                        }
                                    }, 7000);
                                }
                            }
                            break;
                        }
                        switch (mLastHidConfCmd) {
//                            case ARCommon.ARSTACK_CONF_CMD_GET_FACE_SERVICE: {
//                                Common.ARConf_RetData retData = gson.fromJson(msg1, Common.ARConf_RetData.class);
//                                try {
//                                    Log.d(TAG, "retData.data: " + retData.data.toString());
//                                    JSONObject json = new JSONObject(retData.data.toString());
//                                    String sservice = json.getString("serviceSelect");
//                                    //spinner_FaceService.setSelection(Arrays.asList(Common.ARConf_FaceService).indexOf(sservice));
//                                } catch (JSONException e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                            break;
                            case ARCommon.ARSTACK_CONF_CMD_GET_FACE_FILTER:{
                                Common.ARConf_RetData retData = gson.fromJson(msg1, Common.ARConf_RetData.class);
                                try {
                                    Log.d(TAG, "retData.data: " + retData.data.toString());
                                    JSONObject json = new JSONObject(retData.data.toString());
                                    JSONObject captureFilter = json.getJSONObject("captureFilter");
                                    editText_blurThreshold.setText(String.valueOf(captureFilter.getInt("blurThreshold")));
                                    editText_frontThreshold.setText(String.valueOf(captureFilter.getInt("frontThreshold")));
                                    editText_scoreThreshold.setText(String.valueOf(captureFilter.getInt("scoreThreshold")));
                                    editText_heightMaxValue.setText(String.valueOf(captureFilter.getInt("heightMaxValue")));
                                    editText_heightMinValue.setText(String.valueOf(captureFilter.getInt("heightMinValue")));
                                    editText_widthMaxValue.setText(String.valueOf(captureFilter.getInt("widthMaxValue")));
                                    editText_widthMinValue.setText(String.valueOf(captureFilter.getInt("widthMinValue")));
                                    editText_pitchMaxValue.setText(String.valueOf(captureFilter.getInt("pitchMaxValue")));
                                    editText_pitchMinValue.setText(String.valueOf(captureFilter.getInt("pitchMinValue")));
                                    editText_rollMaxValue.setText(String.valueOf(captureFilter.getInt("rollMaxValue")));
                                    editText_rollMinValue.setText(String.valueOf(captureFilter.getInt("rollMinValue")));
                                    editText_yawMaxValue.setText(String.valueOf(captureFilter.getInt("yawMaxValue")));
                                    editText_yawMinValue.setText(String.valueOf(captureFilter.getInt("yawMinValue")));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            break;
                            case ARCommon.ARSTACK_CONF_CMD_GET_COMMON_SETTING:{
                                Common.ARConf_RetData retData = gson.fromJson(msg1, Common.ARConf_RetData.class);
                                try {
                                    Log.d(TAG, "retData.data: " + retData.data.toString());
                                    JSONObject json = new JSONObject(retData.data.toString());
                                    JSONObject commonSettings = json.getJSONObject("commonSettings");
                                    switch_faceAEEnabled.setChecked(commonSettings.getBoolean("faceAEEnabled"));
                                    switch_attributeRecog.setChecked(commonSettings.getBoolean("attributeRecog"));
                                    switch_attributeTrack.setChecked(commonSettings.getBoolean("attributeTrack"));
                                    switch_countAlgorithm.setChecked(commonSettings.getBoolean("countAlgorithm"));
                                    editText_scoringInterval.setText(String.valueOf(commonSettings.getInt("scoringInterval")));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                break;
                            }
                            default:
                                break;
                        }
                    default:
                        break;
                }
            }
        });
    }

    @Override
    public void onChoseFileClick(DialogFragment dialog, String filename) {
        Log.i(TAG,String.format("File********%s",filename));
        if(filename!=null){
            if(transMode==0){
                hidTransfer.TransFirmware(filename);
            }
            else{
                hidTransfer.TransFile(filename);
            }
        }
    }
}
